<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>喜欢玩CS</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#1E40AF',
                        secondary: '#3B82F6',
                        accent: '#22C55E',
                        danger: '#EF4444',
                        neutral: '#1F2937',
                        'neutral-light': '#F3F4F6',
                    },
                    fontFamily: {
                        sans: ['Inter', 'system-ui', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }

            .card-shadow {
                box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
            }

            .transition-all-300 {
                transition: all 0.3s ease;
            }

            .hover-scale {
                transition: transform 0.2s ease-in-out;
            }

            .hover-scale:hover {
                transform: scale(1.02);
            }


            /* 统一单元格内边距 */
            td, th {
                padding: 0.75rem 1rem;
            }
        }
    </style>
</head>
<body class="bg-gray-50 font-sans">
<!-- 顶部导航栏 -->
<nav class="bg-primary text-white shadow-lg fixed w-full top-0 z-50">

</nav>

<!-- 主内容区 -->
<div class="w-full max-w-none w-[80%] px-4 pt-24 pb-12"> <!-- 移除最大宽度限制 -->
    <!-- 数据概览卡片 -->
    <!-- 修改后 -->
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 mb-8">
        <div class="bg-white rounded-xl p-6 card-shadow hover-scale">
            <div class="flex justify-between items-start">
                <div>
                    <p class="text-gray-500 font-medium">当前持有饰品数量</p>
                    <h3 class="text-3xl font-bold mt-1" id="holding-count">0</h3>
                </div>
                <div class="bg-blue-100 p-3 rounded-lg">
                    <i class="fa fa-cubes text-primary text-xl"></i>
                </div>
            </div>
        </div>

        <!-- 新增：当前持有总价值卡片 -->
        <div class="bg-white rounded-xl p-6 card-shadow hover-scale">
            <div class="flex justify-between items-start">
                <div>
                    <p class="text-gray-500 font-medium">当前持有总价值</p>
                    <h3 class="text-3xl font-bold mt-1" id="holding-value">¥0.00</h3>
                </div>
                <div class="bg-purple-100 p-3 rounded-lg">
                    <i class="fa fa-money text-purple-600 text-xl"></i>
                </div>
            </div>
        </div>

        <div class="bg-white rounded-xl p-6 card-shadow hover-scale">
            <div class="flex justify-between items-start">
                <div>
                    <p class="text-gray-500 font-medium">已售出总盈利</p>
                    <h3 class="text-3xl font-bold mt-1 text-accent" id="total-profit">¥0.00</h3>
                </div>
                <div class="bg-green-100 p-3 rounded-lg">
                    <i class="fa fa-line-chart text-accent text-xl"></i>
                </div>
            </div>
        </div>
    </div>

    <!-- 操作按钮和筛选区 -->
    <div class="flex flex-col md:flex-row justify-between items-start md:items-center mb-6 gap-4">
        <div class="flex items-center space-x-3 w-full md:w-auto">
            <button id="add-item-btn"
                    class="bg-primary hover:bg-primary/90 text-white px-4 py-2 rounded-lg flex items-center transition-all-300 shadow-md">
                <i class="fa fa-plus mr-2"></i> 添加饰品
            </button>
        </div>

        <div class="flex items-center space-x-3 w-full md:w-auto">
            <div class="relative w-full md:w-64">
                <input type="text" id="search-input" placeholder="搜索饰品名称..."
                       class="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50">
                <i class="fa fa-search absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
            </div>

            <select id="status-filter"
                    class="bg-white border border-gray-300 text-gray-700 px-4 py-2 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50">
                <option value="all">全部状态</option>
                <option value="1">持有中</option>
                <option value="2">部分已售出</option>
                <option value="3">已售罄</option>
            </select>
        </div>
    </div>

    <!-- 饰品列表 -->
    <div class="bg-white rounded-xl shadow-lg overflow-hidden">
        <div class="w-full min-w-[1400px]"> <!-- 增加足够宽的最小宽度 -->
            <table class="min-w-full divide-y divide-gray-200">
                <!-- 饰品列表表格表头 -->
                <thead class="bg-gray-50">
                <tr>
                    <th scope="col"
                        class="px-6 py-4 text-left text-sm font-medium text-gray-500 uppercase tracking-wider whitespace-nowrap">
                        饰品图片
                    </th> <!-- 新增 -->
                    <th scope="col"
                        class="px-6 py-4 text-left text-sm font-medium text-gray-500 uppercase tracking-wider whitespace-nowrap">
                        饰品名称
                    </th>
                    <th scope="col"
                        class="px-6 py-4 text-left text-sm font-medium text-gray-500 uppercase tracking-wider whitespace-nowrap">
                        购入单价
                    </th>
                    <th scope="col"
                        class="px-6 py-4 text-left text-sm font-medium text-gray-500 uppercase tracking-wider whitespace-nowrap">
                        购入时间
                    </th>
                    <th scope="col"
                        class="px-6 py-4 text-left text-sm font-medium text-gray-500 uppercase tracking-wider whitespace-nowrap">
                        总数量
                    </th>
                    <th scope="col"
                        class="px-6 py-4 text-left text-sm font-medium text-gray-500 uppercase tracking-wider whitespace-nowrap">
                        购入总价格
                    </th>
                    <th scope="col"
                        class="px-6 py-4 text-left text-sm font-medium text-gray-500 uppercase tracking-wider whitespace-nowrap">
                        已售出数量
                    </th>
                    <th scope="col"
                        class="px-6 py-4 text-left text-sm font-medium text-gray-500 uppercase tracking-wider whitespace-nowrap">
                        售出平均价
                    </th>
                    <th scope="col"
                        class="px-6 py-4 text-left text-sm font-medium text-gray-500 uppercase tracking-wider whitespace-nowrap">
                        售出总价格
                    </th>
                    <th scope="col"
                        class="px-6 py-4 text-left text-sm font-medium text-gray-500 uppercase tracking-wider whitespace-nowrap">
                        盈亏
                    </th>
                    <th scope="col"
                        class="px-6 py-4 text-left text-sm font-medium text-gray-500 uppercase tracking-wider whitespace-nowrap">
                        在售价格（yyyp）
                    </th> <!-- 新增 -->
                    <th scope="col"
                        class="px-6 py-4 text-left text-sm font-medium text-gray-500 uppercase tracking-wider whitespace-nowrap">
                        状态
                    </th>
                    <th scope="col"
                        class="px-6 py-4 text-right text-sm font-medium text-gray-500 uppercase tracking-wider whitespace-nowrap">
                        操作
                    </th>
                </tr>
                </thead>
                <tbody id="items-table-body" class="bg-white divide-y divide-gray-200">
                <!-- 表格内容将通过JavaScript动态生成 -->
                <tr class="text-center">
                    <td colspan="12" class="px-6 py-12 text-gray-500">
                        <div class="flex flex-col items-center">
                            <i class="fa fa-inbox text-4xl mb-3 text-gray-300"></i>
                            <p>暂无饰品记录</p>
                            <p class="text-sm mt-1">点击"添加饰品"按钮开始记录</p>
                        </div>
                    </td>
                </tr>
                </tbody>
            </table>
        </div>

        <!-- 分页控件 -->
        <div class="px-6 py-4 border-t border-gray-200 flex items-center justify-between">
            <div class="flex-1 flex justify-between sm:hidden">
                <button id="prev-page-sm"
                        class="relative inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50">
                    上一页
                </button>
                <button id="next-page-sm"
                        class="ml-3 relative inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50">
                    下一页
                </button>
            </div>
            <div class="hidden sm:flex-1 sm:flex sm:items-center sm:justify-between">
                <div>
                    <p class="text-sm text-gray-700">
                        显示第 <span class="font-medium" id="page-start">1</span> 到 <span class="font-medium"
                                                                                       id="page-end">0</span> 条，共
                        <span class="font-medium" id="total-items">0</span> 条记录
                    </p>
                </div>
                <div id="pagination-controls">
                    <nav class="relative z-0 inline-flex rounded-md shadow-sm -space-x-px" aria-label="Pagination">
                        <button id="prev-page-lg"
                                class="relative inline-flex items-center px-2 py-2 rounded-l-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50">
                            <span class="sr-only">上一页</span>
                            <i class="fa fa-chevron-left text-xs"></i>
                        </button>
                        <button class="relative inline-flex items-center px-4 py-2 border border-gray-300 bg-primary text-sm font-medium text-white">
                            1
                        </button>
                        <button id="next-page-lg"
                                class="relative inline-flex items-center px-2 py-2 rounded-r-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50">
                            <span class="sr-only">下一页</span>
                            <i class="fa fa-chevron-right text-xs"></i>
                        </button>
                    </nav>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 添加/编辑饰品模态框 -->
<div id="item-modal" class="fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center hidden">
    <div class="bg-white rounded-xl shadow-xl max-w-md w-full mx-4 transform transition-all">
        <div class="p-6">
            <div class="flex justify-between items-center mb-4">
                <h3 class="text-xl font-bold text-gray-900" id="modal-title">添加饰品</h3>
                <button id="close-modal" class="text-gray-400 hover:text-gray-500 focus:outline-none">
                    <i class="fa fa-times text-xl"></i>
                </button>
            </div>

            <form id="item-form">
                <input type="hidden" id="item-id">
                <input type="hidden" id="user-id"> <!-- 用于存储当前用户ID -->
                <input type="hidden" id="selected-market-hash-name"> <!-- 新增：存储market_hash_name -->
                <div class="mb-4">
                    <label for="item-name-search" class="block text-sm font-medium text-gray-700 mb-1">饰品名称 <span
                            class="text-red-500">*</span></label>
                    <div class="relative">
                        <input
                                type="text"
                                id="item-name-search"
                                placeholder="输入饰品名称搜索（如：蝴蝶刀、AWP）"
                                class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50"
                        >
                        <div id="search-loading" class="absolute right-3 top-1/2 transform -translate-y-1/2 hidden">
                            <i class="fa fa-spinner fa-spin text-gray-400"></i>
                        </div>
                    </div>
                    <div id="search-results"
                         class="mt-1 border border-gray-200 rounded-lg max-h-60 overflow-y-auto hidden z-10 bg-white absolute w-full">
                        <div class="p-3 text-gray-500 text-center" id="search-results-placeholder">
                            请输入关键词搜索饰品
                        </div>
                    </div>
                    <input type="hidden" id="selected-item-id">
                    <input type="hidden" id="selected-item-name">
                </div>

                <div class="mb-4">
                    <label for="buy-price" class="block text-sm font-medium text-gray-700 mb-1">购入单价 <span
                            class="text-red-500">*</span></label>
                    <div class="relative">
                        <span class="absolute inset-y-0 left-0 pl-3 flex items-center text-gray-500">¥</span>
                        <input type="number" id="buy-price" min="0" step="0.01"
                               class="w-full pl-8 pr-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50"
                               required>
                    </div>
                </div>

                <!-- 总数量 -->
                <div class="mb-4">
                    <label for="total-quantity" class="block text-sm font-medium text-gray-700 mb-1">总数量 <span
                            class="text-red-500">*</span></label>
                    <input type="number" id="total-quantity" min="1" value="1"
                           class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50"
                           required>
                </div>

                <div class="mb-4">
                    <label for="buy-date" class="block text-sm font-medium text-gray-700 mb-1">购入时间</label>
                    <input type="date" id="buy-date"
                           class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50">
                </div>

                <!-- 在item-form的保存按钮处修改 -->
                <div class="flex justify-end space-x-3 mt-6">
                    <button type="button" id="cancel-btn"
                            class="px-4 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50 transition-all-300">
                        取消
                    </button>
                    <button type="submit" id="save-item-btn"
                            class="px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary/90 transition-all-300 flex items-center">
                        <span>保存</span>
                        <!-- 加载动画（默认隐藏） -->
                        <span id="save-item-loading" class="ml-2 hidden">
            <i class="fa fa-spinner fa-spin"></i>
        </span>
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- 确认模态框 -->
<div id="confirm-modal" class="fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center hidden">
    <div class="bg-white rounded-xl shadow-xl max-w-md w-full mx-4 transform transition-all">
        <div class="p-6">
            <div class="text-center mb-4">
                <div class="inline-flex items-center justify-center w-12 h-12 rounded-full bg-red-100 mb-4">
                    <i class="fa fa-exclamation-triangle text-red-500 text-xl"></i>
                </div>
                <h3 class="text-lg font-bold text-gray-900" id="confirm-title">确认操作</h3>
                <p class="text-gray-500 mt-2" id="confirm-message">你确定要执行此操作吗？</p>
            </div>

            <div class="flex justify-center space-x-3 mt-6">
                <button id="confirm-cancel"
                        class="px-4 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50 transition-all-300">
                    取消
                </button>
                <button id="confirm-yes"
                        class="px-4 py-2 bg-red-500 text-white rounded-lg hover:bg-red-600 transition-all-300">确认
                </button>
            </div>
        </div>
    </div>
</div>

<!-- 通知提示 -->
<div id="notification"
     class="fixed top-4 right-4 bg-white rounded-lg shadow-lg p-4 max-w-sm transform transition-all duration-300 translate-x-full z-50 flex items-start">
    <div id="notification-icon" class="mr-3 mt-1 text-green-500">
        <i class="fa fa-check-circle text-xl"></i>
    </div>
    <div>
        <h4 id="notification-title" class="font-medium text-gray-900">操作成功</h4>
        <p id="notification-message" class="text-sm text-gray-500 mt-1">饰品已成功添加</p>
    </div>
    <button id="close-notification" class="ml-4 text-gray-400 hover:text-gray-500 focus:outline-none">
        <i class="fa fa-times"></i>
    </button>
</div>

<!-- 售出饰品模态框 -->
<div id="sell-modal" class="fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center hidden">
    <div class="bg-white rounded-xl shadow-xl max-w-md w-full mx-4 transform transition-all">
        <div class="p-6">
            <div class="flex justify-between items-center mb-4">
                <h3 class="text-xl font-bold text-gray-900">记录售出</h3>
                <button id="close-sell-modal" class="text-gray-400 hover:text-gray-500 focus:outline-none">
                    <i class="fa fa-times text-xl"></i>
                </button>
            </div>

            <form id="sell-form">
                <input type="hidden" id="sell-item-id">
                <input type="hidden" id="sell-item-name">
                <input type="hidden" id="sell-total-quantity">

                <div class="mb-4">
                    <label for="sell-quantity" class="block text-sm font-medium text-gray-700 mb-1">售出数量 <span
                            class="text-red-500">*</span></label>
                    <input type="number" id="sell-quantity" min="1" max="999"
                           class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50"
                           required>
                </div>

                <div class="mb-4">
                    <label for="sell-price" class="block text-sm font-medium text-gray-700 mb-1">售出单价 <span
                            class="text-red-500">*</span></label>
                    <div class="relative">
                        <span class="absolute inset-y-0 left-0 pl-3 flex items-center text-gray-500">¥</span>
                        <input type="number" id="sell-price" min="0" step="0.01"
                               class="w-full pl-8 pr-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50"
                               required>
                    </div>
                </div>

                <!-- 在sell-form的保存按钮处修改 -->
                <div class="flex justify-end space-x-3 mt-6">
                    <button type="button" id="cancel-sell-btn"
                            class="px-4 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50 transition-all-300">
                        取消
                    </button>
                    <button type="submit" id="sell-item-btn"
                            class="px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary/90 transition-all-300 flex items-center">
                        <span>保存</span>
                        <!-- 加载动画（默认隐藏） -->
                        <span id="sell-item-loading" class="ml-2 hidden">
            <i class="fa fa-spinner fa-spin"></i>
        </span>
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
    // 全局状态
    let currentPage = 0; // 当前页码（从0开始）
    let totalPages = 0;  // 总页数
    let pageSize = 10;   // 每页条数
    let currentUserId = null; // 当前用户ID

    // 搜索相关DOM元素
    const itemNameSearch = document.getElementById('item-name-search');
    const searchLoading = document.getElementById('search-loading');
    const searchResults = document.getElementById('search-results');
    const searchResultsPlaceholder = document.getElementById('search-results-placeholder');
    const selectedItemId = document.getElementById('selected-item-id');
    const selectedItemName = document.getElementById('selected-item-name');

    // 核心DOM元素
    const itemsTableBody = document.getElementById('items-table-body');
    const addItemBtn = document.getElementById('add-item-btn');
    const itemModal = document.getElementById('item-modal');
    const closeModal = document.getElementById('close-modal');
    const cancelBtn = document.getElementById('cancel-btn');
    const itemForm = document.getElementById('item-form');
    const modalTitle = document.getElementById('modal-title');
    const itemId = document.getElementById('item-id');
    const userId = document.getElementById('user-id');
    const buyPrice = document.getElementById('buy-price');
    const buyDate = document.getElementById('buy-date');
    const confirmModal = document.getElementById('confirm-modal');
    const confirmTitle = document.getElementById('confirm-title');
    const confirmMessage = document.getElementById('confirm-message');
    const confirmYes = document.getElementById('confirm-yes');
    const confirmCancel = document.getElementById('confirm-cancel');
    const logoutBtn = document.getElementById('logout-btn');
    const notification = document.getElementById('notification');
    const notificationTitle = document.getElementById('notification-title');
    const notificationMessage = document.getElementById('notification-message');
    const notificationIcon = document.getElementById('notification-icon');
    const closeNotification = document.getElementById('close-notification');
    const statusFilter = document.getElementById('status-filter');
    const searchInput = document.getElementById('search-input');
    const currentDate = document.getElementById('current-date');
    const currentUsername = document.getElementById('current-username');
    const holdingCount = document.getElementById('holding-count');
    const soldCount = document.getElementById('sold-count');
    const totalProfit = document.getElementById('total-profit');
    const roi = document.getElementById('roi');
    const totalItems = document.getElementById('total-items');
    const pageStart = document.getElementById('page-start');
    const pageEnd = document.getElementById('page-end');
    const prevPageSm = document.getElementById('prev-page-sm');
    const nextPageSm = document.getElementById('next-page-sm');
    const prevPageLg = document.getElementById('prev-page-lg');
    const nextPageLg = document.getElementById('next-page-lg');
    const paginationControls = document.getElementById('pagination-controls');

    // 设置当前日期
    const now = new Date();
    const formattedDate = now.toISOString().split('T')[0];
    currentDate.textContent = formattedDate;
    buyDate.value = formattedDate;

    // 根据状态码判断状态文本
    function getStatusText(status) {
        switch (status) {
            case 1:
            case "holding":
                return "持有中";
            case 2:
            case "partially_sold":
                return "部分已售出";
            case 3:
            case "sold_out":
                return "已售罄";
            default:
                return "未知状态";
        }
    }

    // 根据状态返回样式类
    function getStatusClass(status) {
        switch (status) {
            case 1:
            case "holding":
                return "bg-blue-100 text-blue-800";
            case 2:
            case "partially_sold":
                return "bg-yellow-100 text-yellow-800";
            case 3:
            case "sold_out":
                return "bg-green-100 text-green-800";
            default:
                return "bg-gray-100 text-gray-800";
        }
    }

    // 从后端获取当前登录用户信息
    function loadUserInfo() {
        fetch('/api/auth/current-user', {
            method: 'GET',
            credentials: 'include'
        })
            .then(response => {
                if (!response.ok) {
                    if (response.status === 401) {
                        window.location.href = '/login';
                        return Promise.reject('未登录');
                    }
                    throw new Error('获取用户信息失败');
                }
                return response.text();
            })
            .then(username => {
                // 设置用户名和用户ID
                // document.getElementById('current-username').innerHTML =
                //     `<i class="fa fa-user-circle mr-1"></i> ${username}`;

                document.getElementById('username-display').textContent = username;
                currentUserId = username;
                userId.value = username;

                // 关键修改：在用户信息加载完成后再获取统计数据
                fetchStats();

                // 加载饰品数据
                fetchItems();
            })
            .catch(error => {
                console.error('加载用户信息失败:', error);
                document.getElementById('current-username').innerHTML =
                    `<i class="fa fa-user-circle mr-1"></i> 请重新登录`;
            });
    }

    // 初始化页面
    function init() {
        loadUserInfo();  // 先加载用户信息
        //fetchStats();    // 获取统计数据
        setupEventListeners();  // 设置事件监听器
    }

    // 全局变量，跟踪价格加载状态
    let priceLoadingStatus = {
        totalItems: 0,
        loadedItems: 0,
        isLoading: false
    };

    // 修改fetchItems函数中的状态参数处理
    function fetchItems() {
        if (!currentUserId) {
            console.error('用户ID未设置，无法获取饰品数据');
            itemsTableBody.innerHTML = `
            <tr class="text-center">
                <td colspan="12" class="px-6 py-12 text-gray-500">
                    <div class="flex flex-col items-center">
                        <i class="fa fa-exclamation-triangle text-4xl mb-3 text-gray-300"></i>
                        <p>用户未登录，请刷新页面</p>
                    </div>
                </td>
            </tr>
        `;
            return;
        }

        const filter = statusFilter.value;
        const searchTerm = searchInput.value.trim();
        const sort = 'buyTime';
        const direction = 'DESC';

        // 显示加载状态
        itemsTableBody.innerHTML = `
        <tr class="text-center">
            <td colspan="12" class="px-6 py-12 text-gray-500">
                <div class="flex flex-col items-center">
                    <i class="fa fa-spinner fa-spin text-4xl mb-3 text-gray-300"></i>
                    <p>加载中...</p>
                </div>
            </td>
        </tr>
    `;

        // 构建API URL
        let apiUrl = `/api/items/user/${currentUserId}?page=${currentPage}&size=${pageSize}`;

        // 使用映射后的状态值
        const backendStatus = mapStatusToBackendFormat(filter);
        if (backendStatus) {
            apiUrl += `&status=${backendStatus}`;
        }

        if (searchTerm) {
            apiUrl += `&search=${encodeURIComponent(searchTerm)}`;
        }
        if (sort) {
            apiUrl += `&sort=${sort}`;
        }
        if (direction) {
            apiUrl += `&direction=${direction}`;
        }

        fetch(apiUrl, {
            method: 'GET',
            credentials: 'include'
        })
            .then(response => {
                if (!response.ok) {
                    throw new Error('获取饰品数据失败');
                }
                return response.json();
            })
            .then(data => {
                renderItems(data.content);
                updatePagination(data);
                updateHoldingValue(); // 新增：更新持有总价值

                // 新增：获取批量价格
                if (data.content && data.content.length > 0) {
                    fetchBatchPrices(data.content);
                }
            })
            .catch(error => {
                console.error('获取饰品数据错误:', error);
                itemsTableBody.innerHTML = `
                <tr class="text-center">
                    <td colspan="12" class="px-6 py-12 text-gray-500">
                        <div class="flex flex-col items-center">
                            <i class="fa fa-exclamation-triangle text-4xl mb-3 text-gray-300"></i>
                            <p>加载饰品数据失败</p>
                            <p class="text-sm mt-1">请稍后重试</p>
                        </div>
                    </td>
                </tr>
            `;
            });
    }

    // 渲染饰品列表（修改后）
    function renderItems(items) {
        if (items.length === 0) {
            itemsTableBody.innerHTML = `
        <tr class="text-center">
            <td colspan="12" class="px-6 py-12 text-gray-500">
                <div class="flex flex-col items-center">
                    <i class="fa fa-inbox text-4xl mb-3 text-gray-300"></i>
                    <p>暂无饰品记录</p>
                    <p class="text-sm mt-1">点击"添加饰品"按钮开始记录</p>
                </div>
            </td>
        </tr>
        `;
            return;
        }

        let html = '';
        items.forEach(item => {
            const itemId = `item-${item.id}`;
            const statusText = getStatusText(item.status);
            const statusClass = getStatusClass(item.status);
            const buyTotal = item.buyPrice * item.totalQuantity;
            const sellTotal = (item.sellPrice || 0) * (item.soldQuantity || 0);
            let profitHtml = '-';

            if (item.soldQuantity > 0) {
                const profit = sellTotal - buyTotal;
                const arrowClass = profit >= 0 ? 'fa-arrow-up' : 'fa-arrow-down';
                const profitClass = profit >= 0 ? 'text-danger' : 'text-accent';
                profitHtml = `<div class="text-sm ${profitClass}"><i class="fa ${arrowClass} mr-1"></i> ¥${Math.abs(profit).toFixed(2)}</div>`;
            }

            html += `
        <tr class="hover:bg-gray-50 transition-all-300" id="${itemId}">
            <td class="px-6 py-4 whitespace-nowrap">
                <div class="flex-shrink-0 h-20 w-20 rounded-md overflow-hidden item-img-container">
                    <img src="${item.imgUrl || 'data:image/svg+xml,%3Csvg xmlns=\'http://www.w3.org/2000/svg\' viewBox=\'0 0 24 24\' fill=\'%23f3f4f6\'%3E%3C/svg%3E'}"
                         class="h-full w-full object-cover item-img-zoom"
                         alt="${item.name}">
                </div>
            </td>
            <td class="px-6 py-4 whitespace-nowrap">
                <div class="text-sm font-medium text-gray-900">${item.name}</div>
                <div class="text-xs text-gray-500">${item.marketHashName || '-'}</div>
            </td>
            <td class="px-6 py-4 whitespace-nowrap">
                <div class="text-sm text-gray-900">¥${item.buyPrice.toFixed(2)}</div>
            </td>
            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                ${item.buyTime ? formatDate(item.buyTime) : '-'}
            </td>
            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                ${item.totalQuantity}
            </td>
            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                ¥${buyTotal.toFixed(2)}
            </td>
            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                ${item.soldQuantity || 0}
            </td>
            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                ${item.sellPrice ? `¥${item.sellPrice.toFixed(2)}` : '-'}
            </td>
            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                ${item.soldQuantity > 0 ? `¥${sellTotal.toFixed(2)}` : '-'}
            </td>
            <td class="px-6 py-4 whitespace-nowrap">
                ${profitHtml}
            </td>
            <td class="px-6 py-4 whitespace-nowrap">
                <div class="text-sm text-gray-500" id="${itemId}-price">加载中...</div>
            </td>
            <td class="px-6 py-4 whitespace-nowrap">
                <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${statusClass}">
                    ${statusText}
                </span>
            </td>
            <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                <button onclick="sellItem(${item.id})" class="text-green-600 hover:text-green-900 mr-3">
                    <i class="fa fa-money"></i> 售出
                </button>
                <button onclick="editItem(${item.id})" class="text-indigo-600 hover:text-indigo-900 mr-3">
                    <i class="fa fa-pencil"></i> 编辑
                </button>
                <button onclick="deleteItem(${item.id})" class="text-red-600 hover:text-red-900">
                    <i class="fa fa-trash"></i> 删除
                </button>
            </td>
        </tr>
        `;
        });

        itemsTableBody.innerHTML = html;

        // 移除调用fetchRealTimeData的代码
        // 改为使用fetchBatchPrices获取价格数据
        if (items.length > 0) {
            fetchBatchPrices(items);
        }
    }

        // 售出饰品
        function sellItem(id) {
            fetch(`/api/items/${id}`, {
                method: 'GET',
                credentials: 'include'
            })
                .then(response => response.json())
                .then(item => {
                    document.getElementById('sell-item-id').value = item.id;
                    document.getElementById('sell-item-name').value = item.name;
                    document.getElementById('sell-total-quantity').value = item.totalQuantity;
                    document.getElementById('sell-quantity').value = 1; // 默认售出1个
                    document.getElementById('sell-price').value = ''; // 清空价格

                    // 计算最大可售数量（总数量 - 已售出数量）
                    const maxSellable = item.totalQuantity - (item.soldQuantity || 0);
                    document.getElementById('sell-quantity').setAttribute('max', maxSellable);

                    // 设置当前已售出数量（用于验证）
                    document.getElementById('sell-quantity').setAttribute('data-sold', item.soldQuantity || 0);

                    // 如果已全部售出，禁止操作
                    if (maxSellable <= 0) {
                        showNotification("提示", "该饰品已全部售出", "info");
                        return;
                    }

                    document.getElementById('sell-modal').classList.remove('hidden');
                    document.body.style.overflow = 'hidden';
                })
                .catch(error => {
                    console.error('获取饰品信息失败:', error);
                    showNotification("错误", "获取饰品信息失败", "error");
                });
        }



    // 只保留这一段事件监听，删除另一段重复的
    document.addEventListener('DOMContentLoaded', () => {
        // 关闭售出模态框
        document.getElementById('close-sell-modal').addEventListener('click', () => {
            document.getElementById('sell-modal').classList.add('hidden');
            document.body.style.overflow = '';
        });

        document.getElementById('cancel-sell-btn').addEventListener('click', () => {
            document.getElementById('sell-modal').classList.add('hidden');
            document.body.style.overflow = '';
        });

        // 提交售出表单（正确的逻辑）
        document.getElementById('sell-form').addEventListener('submit', (e) => {
            e.preventDefault();

            const itemId = document.getElementById('sell-item-id').value;
            const quantity = parseInt(document.getElementById('sell-quantity').value);
            const price = parseFloat(document.getElementById('sell-price').value);

            // 验证数量是否有效
            if (isNaN(quantity) || quantity <= 0) {
                showNotification("错误", "请输入有效的售出数量（必须大于0）", "error");
                return;
            }

            // 正确计算最大可售数量：总数量 - 已售出数量
            const totalQuantity = parseInt(document.getElementById('sell-total-quantity').value);
            const currentSold = parseInt(document.getElementById('sell-quantity').getAttribute('data-sold') || 0);
            const maxSellable = totalQuantity - currentSold;

            // 验证数量是否超过最大可售
            if (quantity > maxSellable) {
                showNotification("错误", `售出数量不能超过 ${maxSellable}（总数量 ${totalQuantity} - 已售出 ${currentSold}）`, "error");
                return;
            }

            // 验证价格是否有效
            if (isNaN(price) || price <= 0) {
                showNotification("错误", "请输入有效的售出单价（必须大于0）", "error");
                return;
            }

            const sellButton = document.getElementById('sell-item-btn');
            const loadingSpan = document.getElementById('sell-item-loading');

            // 禁用按钮并显示加载动画
            sellButton.disabled = true;
            loadingSpan.classList.remove('hidden');

            // 提交售出信息
            fetch(`/api/items/${itemId}/sell`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    soldQuantity: quantity,
                    sellPrice: price
                }),
                credentials: 'include'
            })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('售出饰品失败');
                    }
                    return response.json();
                })
                .then(data => {
                    document.getElementById('sell-modal').classList.add('hidden');
                    document.body.style.overflow = '';
                    showNotification("成功", "售出记录已保存", "success");
                    fetchItems(); // 刷新列表
                    fetchStats(); // 刷新统计数据
                })
                .catch(error => {
                    console.error('售出饰品错误:', error);
                    showNotification("错误", "售出饰品失败，请重试", "error");
                })
                .finally(() => {
                    // 无论成功还是失败，都恢复按钮状态
                    sellButton.disabled = false;
                    loadingSpan.classList.add('hidden');
                });
        });
    });

    // 更新分页控件
    function updatePagination(data) {
        const totalElements = data.totalElements;
        totalPages = data.totalPages;
        const pageNumber = data.number;

        totalItems.textContent = totalElements;

        if (totalElements === 0) {
            pageStart.textContent = "0";
            pageEnd.textContent = "0";
            return;
        }

        pageStart.textContent = (pageNumber * pageSize) + 1;
        pageEnd.textContent = Math.min((pageNumber + 1) * pageSize, totalElements);

        // 更新分页按钮状态
        prevPageSm.disabled = pageNumber === 0;
        prevPageLg.disabled = pageNumber === 0;
        nextPageSm.disabled = pageNumber === totalPages - 1;
        nextPageLg.disabled = pageNumber === totalPages - 1;

        // 构建分页页码
        let paginationHtml = '';
        const maxPages = 5; // 最多显示的页码数
        let startPage = Math.max(0, pageNumber - Math.floor(maxPages / 2));
        let endPage = Math.min(startPage + maxPages - 1, totalPages - 1);

        if (endPage - startPage + 1 < maxPages) {
            startPage = Math.max(0, endPage - maxPages + 1);
        }

        // 第一页按钮
        if (startPage > 0) {
            paginationHtml += `
                <button onclick="goToPage(0)" class="relative inline-flex items-center px-4 py-2 border border-gray-300 bg-white text-sm font-medium text-gray-700 hover:bg-gray-50">
                    1
                </button>
            `;
            if (startPage > 1) {
                paginationHtml += `
                    <span class="relative inline-flex items-center px-4 py-2 border border-gray-300 bg-white text-sm font-medium text-gray-700">
                        ...
                    </span>
                `;
            }
        }

        // 中间页码
        for (let i = startPage; i <= endPage; i++) {
            if (i === pageNumber) {
                paginationHtml += `
                    <button class="relative inline-flex items-center px-4 py-2 border border-gray-300 bg-primary text-sm font-medium text-white">
                        ${i + 1}
                    </button>
                `;
            } else {
                paginationHtml += `
                    <button onclick="goToPage(${i})" class="relative inline-flex items-center px-4 py-2 border border-gray-300 bg-white text-sm font-medium text-gray-700 hover:bg-gray-50">
                        ${i + 1}
                    </button>
                `;
            }
        }

        // 最后一页按钮
        if (endPage < totalPages - 1) {
            if (endPage < totalPages - 2) {
                paginationHtml += `
                    <span class="relative inline-flex items-center px-4 py-2 border border-gray-300 bg-white text-sm font-medium text-gray-700">
                        ...
                    </span>
                `;
            }
            paginationHtml += `
                <button onclick="goToPage(${totalPages - 1})" class="relative inline-flex items-center px-4 py-2 border border-gray-300 bg-white text-sm font-medium text-gray-700 hover:bg-gray-50">
                    ${totalPages}
                </button>
            `;
        }

        paginationControls.innerHTML = `
            <nav class="relative z-0 inline-flex rounded-md shadow-sm -space-x-px" aria-label="Pagination">
                <button id="prev-page-lg" onclick="prevPage()" class="relative inline-flex items-center px-2 py-2 rounded-l-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50 ${pageNumber === 0 ? 'opacity-50 cursor-not-allowed' : ''}">
                    <span class="sr-only">上一页</span>
                    <i class="fa fa-chevron-left text-xs"></i>
                </button>
                ${paginationHtml}
                <button id="next-page-lg" onclick="nextPage()" class="relative inline-flex items-center px-2 py-2 rounded-r-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50 ${pageNumber === totalPages - 1 ? 'opacity-50 cursor-not-allowed' : ''}">
                    <span class="sr-only">下一页</span>
                    <i class="fa fa-chevron-right text-xs"></i>
                </button>
            </nav>
        `;
    }

    // 状态映射函数：将数值状态转换为后端期望的字符串格式
    function mapStatusToBackendFormat(status) {
        switch (status) {
            case "1":
                return "holding";
            case "2":
                return "partially_sold";
            case "3":
                return "sold_out";
            default:
                return null; // 对应"全部状态"选项
        }
    }

    // 前往指定页码
    function goToPage(page) {
        if (page >= 0 && page < totalPages) {
            currentPage = page;
            fetchItems();
        }
    }

    // 上一页
    function prevPage() {
        if (currentPage > 0) {
            currentPage--;
            fetchItems();
        }
    }

    // 带延迟重试的更新总价值函数
    function updateHoldingValue() {
        const items = document.querySelectorAll('tr[id^="item-"]');
        let totalValue = 0;
        let processedItems = 0;

        items.forEach(row => {
            // 获取饰品价格
            const priceElement = row.querySelector('td:nth-child(11) div');
            if (!priceElement || priceElement.textContent === '加载中...') return;

            processedItems++;

            const priceText = priceElement.textContent.replace('¥', '');
            const price = parseFloat(priceText);

            // 获取剩余数量（总数量 - 已售出数量）
            const totalQuantity = parseInt(row.querySelector('td:nth-child(5)').textContent.trim());
            const soldQuantity = parseInt(row.querySelector('td:nth-child(7)').textContent.trim());
            const remaining = totalQuantity - soldQuantity;

            // 计算价值并累加
            if (!isNaN(price) && !isNaN(remaining)) {
                totalValue += price * remaining;
            }
        });

        // 更新UI
        const holdingValueElement = document.getElementById('holding-value');
        const holdingValueCard = holdingValueElement.parentElement;

        if (processedItems < items.length) {
            // 如果还有未加载的价格，显示加载状态并设置延迟重试
            holdingValueCard.classList.add('opacity-70');
            holdingValueElement.textContent = '加载中...';

            // 延迟200ms后重试
            setTimeout(updateHoldingValue, 200);
        } else {
            // 所有价格都已加载，显示最终结果
            holdingValueCard.classList.remove('opacity-70');
            holdingValueElement.textContent = `¥${totalValue.toFixed(2)}`;
        }
    }

    // 下一页
    function nextPage() {
        if (currentPage < totalPages - 1) {
            currentPage++;
            fetchItems();
        }
    }

    // 在JavaScript中添加新的函数来获取批量价格
    // 异步获取价格并更新状态
    async function fetchBatchPrices(items) {
        priceLoadingStatus.totalItems = items.length;
        priceLoadingStatus.loadedItems = 0;
        priceLoadingStatus.isLoading = true;

        try {
            const marketHashNames = items.map(item => item.marketHashName);

            const response = await fetch('/api/batch-prices', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(marketHashNames),
                credentials: 'include'
            });

            if (!response.ok) {
                throw new Error('获取批量价格失败');
            }

            const data = await response.json();

            if (data.code === 200 && data.data && data.data.success) {
                // 更新UI上的价格
                updatePricesInUI(data.data.success);
                priceLoadingStatus.loadedItems = Object.keys(data.data.success).length;
                priceLoadingStatus.isLoading = false;

                // 如果所有价格都已加载，立即更新总价值
                if (priceLoadingStatus.loadedItems === priceLoadingStatus.totalItems) {
                    updateHoldingValue();
                }

                return true;
            } else {
                console.error('获取价格数据格式异常:', data);
                priceLoadingStatus.isLoading = false;
                return false;
            }
        } catch (error) {
            console.error('获取批量价格错误:', error);
            priceLoadingStatus.isLoading = false;
            return false;
        }
    }


    // 全局状态添加加载标志
    let isLoadingItems = false; // 防止重复加载饰品
    let isLoadingPrices = false; // 防止重复加载价格

    // 更新UI上的价格
    function updatePricesInUI(priceData) {
        // 延迟执行以确保DOM已完全渲染
        setTimeout(() => {
            // 遍历每个饰品，更新价格
            for (const marketHashName in priceData) {
                if (priceData.hasOwnProperty(marketHashName)) {
                    const priceInfo = priceData[marketHashName];

                    // 查找所有包含marketHashName的行
                    const itemRows = document.querySelectorAll('tr[id^="item-"]');

                    // 统计成功更新的行数
                    let updatedRows = 0;

                    for (const row of itemRows) {
                        // 获取行中第二个单元格（饰品名称和marketHashName所在的单元格）
                        const secondCell = row.querySelector('td:nth-child(2)');
                        if (!secondCell) continue;

                        // 获取marketHashName元素（通常是第二个div）
                        const marketHashNameElement = secondCell.querySelector('div:nth-child(2)');
                        if (!marketHashNameElement) continue;

                        // 比较内容
                        if (marketHashNameElement.textContent.trim() === marketHashName) {
                            const itemId = row.id;
                            const priceElement = document.getElementById(`${itemId}-price`);
                            if (priceElement && priceInfo.yyypSellPrice) {
                                priceElement.textContent = `¥${priceInfo.yyypSellPrice.toFixed(2)}`;
                                priceElement.className = 'text-sm font-medium text-gray-900';
                                updatedRows++;
                            }
                        }
                    }

                    // 记录日志，用于调试
                    console.log(`处理饰品: ${marketHashName}, 找到 ${updatedRows} 行`);
                }
            }
        }, 500); // 延迟500ms以确保DOM已完全渲染
    }


    // 修改fetchStats函数
    function fetchStats() {
        if (!currentUserId) return;

        fetch(`/api/stats/user/${currentUserId}`, {
            method: 'GET',
            credentials: 'include'
        })
            .then(response => {
                if (!response.ok) {
                    throw new Error('获取统计数据失败');
                }
                return response.json();
            })
            .then(data => {
                const holdingCountValue = data.totalItems;
                holdingCount.textContent = holdingCountValue;

                // 更新已售出数量
                if (document.getElementById('sold-count')) {
                    document.getElementById('sold-count').textContent = data.totalSoldItems || 0;
                }

                // 总盈利
                totalProfit.textContent = `¥${(data.totalProfit || 0).toFixed(2)}`;
            })
            .catch(error => {
                console.error('获取统计数据错误:', error);
            });

        fetch(`/api/stats/user/${currentUserId}`)
            .then(response => response.json())
            .then(data => {
                // 总盈利
                const profit = data.totalProfit || 0;
                totalProfit.textContent = `¥${profit.toFixed(2)}`;
                // 根据盈亏值设置颜色（亏损绿色，盈利红色）
                totalProfit.className = profit >= 0 ? 'text-3xl font-bold mt-1 text-danger' : 'text-3xl font-bold mt-1 text-accent';
            })
    }

    // 设置事件监听器
    function setupEventListeners() {
        // 添加饰品按钮
        addItemBtn.addEventListener('click', () => {
            console.log('添加饰品按钮被点击'); // 添加日志，确认事件被触发
            modalTitle.textContent = "添加饰品";
            itemId.value = "";
            itemForm.reset();
            buyDate.value = new Date().toISOString().split('T')[0];
            selectedItemId.value = "";
            selectedItemName.value = "";
            itemModal.classList.remove('hidden');
            document.body.style.overflow = 'hidden';
        });

        // 关闭模态框
        closeModal.addEventListener('click', () => {
            itemModal.classList.add('hidden');
            document.body.style.overflow = '';
            searchResults.classList.add('hidden');
        });

        // 取消按钮
        cancelBtn.addEventListener('click', () => {
            itemModal.classList.add('hidden');
            document.body.style.overflow = '';
            searchResults.classList.add('hidden');
        });

        // 饰品名称搜索
        itemNameSearch.addEventListener('input', debounce(() => {
            const searchTerm = itemNameSearch.value.trim();
            if (searchTerm.length < 2) {
                searchResults.classList.add('hidden');
                return;
            }

            searchLoading.classList.remove('hidden');

            // 调用后端API进行搜索
            fetch(`/api/search-good-id?search=${encodeURIComponent(searchTerm)}`, {
                method: 'GET',
                credentials: 'include'
            })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('搜索饰品失败');
                    }
                    return response.json();
                })
                .then(data => {
                    searchLoading.classList.add('hidden');

                    // 正确处理实际的数据结构
                    const items = data?.data?.data || {};
                    const itemList = Object.values(items);

                    if (itemList.length > 0) {
                        searchResultsPlaceholder.classList.add('hidden');
                        let html = '';
                        // 在饰品名称搜索的响应处理中修改
                        itemList.forEach(item => {
                            html += `
    <div class="px-4 py-2 hover:bg-gray-100 cursor-pointer"
         onclick="selectItem(${item.id}, '${escapeHtml(item.name)}', '${escapeHtml(item.market_hash_name)}')">
        <div class="text-sm font-medium">${escapeHtml(item.name)}</div>
        <div class="text-xs text-gray-500 mt-1">${escapeHtml(item.market_hash_name)}</div>
    </div>
    `;
                        });
                        searchResults.innerHTML = html;
                    } else {
                        searchResultsPlaceholder.textContent = "未找到匹配的饰品";
                        searchResultsPlaceholder.classList.remove('hidden');
                    }

                    searchResults.classList.remove('hidden');
                })
                .catch(error => {
                    searchLoading.classList.add('hidden');
                    searchResultsPlaceholder.textContent = "搜索失败，请重试";
                    searchResultsPlaceholder.classList.remove('hidden');
                    searchResults.classList.remove('hidden');
                    console.error('搜索饰品错误:', error);
                });
        }, 300));

        // 添加HTML转义函数，防止XSS攻击
        function escapeHtml(text) {
            return text
                .replace(/&/g, "&amp;")
                .replace(/</g, "&lt;")
                .replace(/>/g, "&gt;")
                .replace(/"/g, "&quot;")
                .replace(/'/g, "&#039;");
        }

        // 点击页面其他区域关闭搜索结果
        document.addEventListener('click', (e) => {
            if (!itemNameSearch.contains(e.target) && !searchResults.contains(e.target)) {
                searchResults.classList.add('hidden');
            }
        });

        itemForm.addEventListener('submit', (e) => {
            e.preventDefault();

            if (!selectedItemId.value) {
                showNotification("错误", "请选择饰品名称", "error");
                return;
            }

            const saveButton = document.getElementById('save-item-btn');
            const loadingSpan = document.getElementById('save-item-loading');

            // 禁用按钮并显示加载动画
            saveButton.disabled = true;
            loadingSpan.classList.remove('hidden');

            const formData = {
                id: itemId.value || null,
                userId: currentUserId,
                name: selectedItemName.value,
                buyPrice: parseFloat(buyPrice.value),
                totalQuantity: parseInt(document.getElementById('total-quantity').value),
                soldQuantity: 0,
                buyDate: buyDate.value,
                sellPrice: null,
                sellDate: null,
                goodId: parseInt(selectedItemId.value),
                marketHashName: document.getElementById('selected-market-hash-name').value
            };

            const url = itemId.value ? `/api/items/${itemId.value}` : `/api/items`;
            const method = itemId.value ? 'PUT' : 'POST';

            fetch(url, {
                method: method,
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify(formData),
                credentials: 'include'
            })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('保存饰品失败');
                    }
                    return response.json();
                })
                .then(data => {
                    itemModal.classList.add('hidden');
                    document.body.style.overflow = '';
                    showNotification("成功", itemId.value ? "饰品已更新" : "饰品已添加", "success");
                    fetchItems();
                    fetchStats();
                })
                .catch(error => {
                    console.error('保存饰品错误:', error);
                    showNotification("错误", "保存饰品失败，请重试", "error");
                })
                .finally(() => {
                    // 无论成功还是失败，都恢复按钮状态
                    saveButton.disabled = false;
                    loadingSpan.classList.add('hidden');
                });
        });

        // 确认删除饰品
        confirmYes.addEventListener('click', () => {
            if (confirmModal.dataset.action === 'delete') {
                const itemId = confirmModal.dataset.itemId;
                fetch(`/api/items/${itemId}`, {
                    method: 'DELETE',
                    credentials: 'include'
                })
                    .then(response => {
                        if (!response.ok) {
                            throw new Error('删除饰品失败');
                        }
                        showNotification("成功", "饰品记录已删除", "success");
                        fetchItems();
                        fetchStats();
                    })
                    .catch(error => {
                        console.error('删除饰品错误:', error);
                        showNotification("错误", "删除饰品失败，请重试", "error");
                    });
            }
            confirmModal.classList.add('hidden');
        });

        // 确认模态框 - 取消按钮
        confirmCancel.addEventListener('click', () => {
            confirmModal.classList.add('hidden');
        });

        // 退出登录
        logoutBtn.addEventListener('click', () => {
            fetch('/logout', {
                method: 'POST',
                credentials: 'include'
            })
                .then(() => {
                    window.location.href = '/login';
                })
                .catch(error => {
                    console.error('退出登录错误:', error);
                    showNotification("错误", "退出登录失败，请重试", "error");
                });
        });

        // 筛选和搜索
        statusFilter.addEventListener('change', () => {
            currentPage = 0;
            fetchItems();
        });

        searchInput.addEventListener('input', debounce(() => {
            currentPage = 0;
            fetchItems();
        }, 300));

        // 关闭通知
        closeNotification.addEventListener('click', () => {
            notification.classList.add('translate-x-full');
        });
    }

    // 选择饰品（修改此函数）
    function selectItem(id, name, marketHashName) { // 新增参数接收market_hash_name
        selectedItemId.value = id;
        selectedItemName.value = name;
        document.getElementById('selected-market-hash-name').value = marketHashName; // 保存到隐藏字段
        itemNameSearch.value = name;
        searchResults.classList.add('hidden');
    }

    // 显示通知
    function showNotification(title, message, type = "success") {
        notificationTitle.textContent = title;
        notificationMessage.textContent = message;

        // 设置图标和颜色
        if (type === "success") {
            notificationIcon.innerHTML = '<i class="fa fa-check-circle text-xl text-green-500"></i>';
        } else if (type === "error") {
            notificationIcon.innerHTML = '<i class="fa fa-times-circle text-xl text-red-500"></i>';
        } else if (type === "warning") {
            notificationIcon.innerHTML = '<i class="fa fa-exclamation-circle text-xl text-yellow-500"></i>';
        } else if (type === "info") {
            notificationIcon.innerHTML = '<i class="fa fa-info-circle text-xl text-blue-500"></i>';
        }

        // 显示通知
        notification.classList.remove('translate-x-full');

        // 3秒后自动关闭
        setTimeout(() => {
            notification.classList.add('translate-x-full');
        }, 3000);
    }

    // 防抖函数
    function debounce(func, delay) {
        let timer;
        return function () {
            const context = this;
            const args = arguments;
            clearTimeout(timer);
            timer = setTimeout(() => {
                func.apply(context, args);
            }, delay);
        };
    }

    // 编辑饰品函数
    function editItem(id) {
        fetch(`/api/items/${id}`, {
            method: 'GET',
            credentials: 'include'
        })
            .then(response => {
                if (!response.ok) {
                    throw new Error('获取饰品信息失败');
                }
                return response.json();
            })
            .then(item => {
                modalTitle.textContent = "编辑饰品";
                itemId.value = item.id;
                selectedItemId.value = item.id;
                selectedItemName.value = item.name;
                itemNameSearch.value = item.name;
                buyPrice.value = item.buyPrice;
                document.getElementById('total-quantity').value = item.totalQuantity;
                buyDate.value = item.buyDate ? new Date(item.buyDate).toISOString().split('T')[0] : '';

                itemModal.classList.remove('hidden');
                document.body.style.overflow = 'hidden';
            })
            .catch(error => {
                console.error('获取饰品信息错误:', error);
                showNotification("错误", "获取饰品信息失败", "error");
            });
    }

    // 删除饰品函数
    function deleteItem(id) {
        confirmModal.dataset.action = 'delete';
        confirmModal.dataset.itemId = id;
        confirmTitle.textContent = "确认删除";
        confirmMessage.textContent = "你确定要删除这条饰品记录吗？此操作不可撤销。";
        confirmModal.classList.remove('hidden');
    }

    // 格式化日期
    function formatDate(dateString) {
        if (!dateString) return '-';
        const date = new Date(dateString);
        return date.toLocaleDateString();
    }

    // 初始化页面
    document.addEventListener('DOMContentLoaded', init);
</script>
</body>
</html>
